#! /bin/bash

if [ -n "$2" ] ;
then
  do_date=$2
else
  do_date=`date -d '-1 day' +%F`
fi

env_config="
use dw;
SET mapreduce.job.queuename=tianyan;
SET hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat;
SET hive.exec.dynamic.partition.mode=nonstrict;"

app_station_detail="
insert overwrite table dw.app_station_detail partition (dt)
select
       station_id,
       concat_ws(',', collect_set(cast(cart_id as string))) as cart_id,
       collect_set(fuel_no)[0],
       sum(quantity) as fuel_quantity,
       sum(c_pay_money),
       sum(c_discount_money),
       sum(mc_pay_money),
       sum(mc_discount_money),
       concat_ws(',', collect_set(rule_name)) as rule_name,
       concat_ws(',', collect_set(discount_type)) as discount_type,
       concat_ws(',', collect_set(discount_policy)) as discount_policy,
       sum(rebate_money),
       sum(real_rebate_money),
       dsod.dt
from dws_station_order_detail dsod
where dsod.dt in (
            select partition_dt
            from dim_partition
            where business_type = 2 and dt = '$do_date')
group by station_id, dsod.dt;"

app_cart_detail="
insert overwrite table dw.app_cart_detail partition (dt)
select
       cart_id,
       collect_set(fuel_no)[0],
       sum(quantity) as fuel_quantity,
       sum(c_pay_money),
       sum(c_discount_money),
       sum(mc_pay_money),
       sum(mc_discount_money),
       concat_ws(',', collect_set(rule_name)) as rule_name,
       concat_ws(',', collect_set(discount_type)) as discount_type,
       concat_ws(',', collect_set(discount_policy)) as discount_policy,
       sum(rebate_money),
       sum(real_rebate_money),
       dsod.dt
from dws_station_order_detail dsod
where dsod.dt in (
            select partition_dt
            from dim_partition
            where business_type = 2 and dt = '$do_date')
group by cart_id, dsod.dt;"

insert_into_table(){
  case $1 in
  "all")
      echo $1
      hive -e "$env_config$app_cart_detail$app_station_detail$tmp_cart_detail$tmp_station_detail"
    ;;
  "app_station_detail")
      echo $1
      hive -e "$env_config$app_station_detail"
  ;;
  "app_cart_detail")
      echo $1
      hive -e "$env_config$app_cart_detail"
  ;;
  esac
}